/* 
 * File:   Server.h
 * Author: JM, Michał Kołodziejski
 *
 * Created on 13 maj 2010, 14:35
 */

#ifndef _SERVER_H
#define	_SERVER_H
#include <string>
#include <vector>
#include <list>
#include "TMessage.h"
#include "standardLindaHeaders.h"
#include "ServerDataClasses.h"
#include <boost/smart_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/thread/mutex.hpp>

class Server {
public:
    virtual ~Server();
    void init(const int aQueueId);
    void do_it();
    static void termination_handler(int signum);

public:
    static inline int getQueueId() {
        return iQueueId;
    }

    static Server& getInstance(){
        if(serverInstance == NULL){
            serverInstance = new Server();
        }
        return *serverInstance;
    }

private:
    Server();
    Server(const Server& orig);

    void putMsg(const std::string);
    void readMsg(const enum TReadType aReadType, const int aPrivQueueId, const int aTimeout,
                    const std::string aMessage);

    void reply(const int aPrivQueueId, const int aType, const std::string aMsg) const;
    boost::shared_ptr<TMessage> parseMsg(const std::string) const;
    boost::shared_ptr<std::list<TFilter> > parseFilter(const std::string) const;
    bool isMessageFittingClient(boost::shared_ptr<TMessage> msg, boost::shared_ptr<TClient> client);

    void timeoutThreadLoop();

private:
    static Server* serverInstance;
    static int iQueueId;
    std::list<boost::shared_ptr<TMessage> > iMessages;
    std::list<boost::shared_ptr<TClient> > iWaitingClients;

    // timeout-thread data
    boost::shared_ptr<boost::thread> timeoutThread;
    volatile bool timeoutThreadFinish;
    boost::mutex mutex;
};

class MalformedMessageServerException {
};

#endif	/* _SERVER_H */

